//JavaScript代码区域
layui.use(['element', 'table', 'jquery', 'laydate', 'form'], function () {
    var element = layui.element;
    var table = layui.table;
    var laydate = layui.laydate;
    var form = layui.form;
    // var $ = layui.jquery;
    laydate.render({
        elem: "#start_date"
    })
    laydate.render({
        elem: "#end_date"
    });
    $(function () {
        getLeader();
        getCoach();
        tableRender();
        form.render();
    })
    $("#find").click(function () {
        tableRender();
    })
    $("#clear").click(function () {
        $(".search_input").val("");
    })

    function tableRender() {
        table.render({
            elem: '#demo'
            // , height: 312
            ,
            url: LOCALHOSTURL + '/team/getTeams' //数据接口
            ,
            method: "get",
            where: {
                "param": $("#param").val(),
                "leader": $("#leader").find("option:selected").val(),
                "coach": $("#coach").find("option:selected").val(),
                "start_date": $("#start_date").val(),
                "end_date": $("#end_date").val()
            },
            xhrFields: {
                withCredentials: true //默认情况下，标准的跨域请求是不会发送cookie的
            },
            headers: {
                "Authorization": $.cookie("token")
            },
            crossDomain: true,
            response: {
                statusName: 'code' //规定数据状态的字段名称，默认：code
                ,
                statusCode: 200 //规定成功的状态码，默认：0
            },
            page: true //开启分页
            ,
            title: "小组表",
            toolbar: '#toolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [
                [ //表头
                    {
                        type: 'checkbox',
                        fixed: 'left'
                    }, {
                    field: 'id',
                    title: 'ID',
                    sort: true
                }, {
                    field: 'name',
                    title: '组名',
                    templet: function (res) {
                        if (res.name == null)
                            return '暂无';
                        else
                            return res.name;
                    }
                }, {
                    field: 'description',
                    title: '小组简介',
                    templet: function (res) {
                        if (res.description == null)
                            return '暂无';
                        else
                            return res.description;
                    }
                }, {
                    field: 'leader',
                    title: '组长',
                    templet: function (res) {
                        if (res.leaderName == null || res.leaderName == "")
                            if (res.leader != null && res.leader != "")
                                return res.leader;
                            else
                                return '暂无';
                        else
                            return res.leaderName;
                    }
                }, {
                    field: 'coach',
                    title: '教练',
                    templet: function (res) {
                        if (res.coachName == null || res.coachName == "") {
                            if (res.coach != null && res.coach != "")
                                return res.coach;
                            else
                                return '暂无'
                        } else
                            return res.coachName;
                    }
                }, {
                    field: 'stage',
                    title: '阶段',
                    templet: function (res) {
                        if (res.stage == null)
                            return '暂无';
                        else
                            return res.stage;
                    }
                }, {
                    field: 'clazzRoom',
                    title: '教室',
                    templet: function (res) {
                        if (res.clazzRoom == null)
                            return '暂无';
                        else
                            return res.clazzRoom;
                    }
                }, {
                    field: 'crew',
                    title: '小组人数',
                    sort: true,
                    templet: function (res) {
                        if (res.crew == null)
                            return '暂无';
                        else
                            return res.crew;
                    }
                }, {
                    field: 'createTime',
                    title: '成立时间',
                    templet: function (res) {
                        return res.createTime;
                    }
                }, {
                    fixed: 'right',
                    title: '操作',
                    toolbar: '#barDemo',
                    width: 150
                }
                ]
            ],
            done: function (res) {
                console.log(res);
            }
        });
    }

    //第一个实例

    table.on('toolbar(demo)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        switch (obj.event) {
            case 'add':
                layer.open({
                    type: 2,
                    title: "添加用户信息",
                    area: ['100%', '100%'],
                    content: ["editTeam.html"],
                    shadeClose: true, //点击旁边地方自动关闭
                    //动画
                    anim: 0,
                    success: function (layero, index) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                        body.find("#name").removeAttr("readonly");
                        //将按钮改成添加
                        body.find("#update").html("添加");
                        body.find("#leader").attr("disabled", "disabled");
                        body.find("#update").click(function () {
                            let name = body.find("#name").val();
                            let desc = body.find("#desc").val();
                            let stage = body.find("#stage").val();
                            if (name == '') {
                                layer.msg("组名不能为空", function () {
                                    body.find("#name").focus();
                                })
                            } else if (name != '') {
                                let result = myAjax("/team/getTeamByName", "get", {"name": name});
                                if (result.data == null) {
                                    let teamdata = {
                                        "name": name,
                                        "description": desc,
                                        "stage": stage,
                                        "leader": body.find("#leader").find("option:selected").val(),
                                        "coach": body.find("#coach").find("option:selected").val(),
                                        "clazzRoom": body.find("#clazzRoom").val()
                                    };
                                    console.log(teamdata);
                                    let result = ajaxModel("/team/addTeam", "post", teamdata);
                                    if (result.code == 200) {
                                        layer.alert(result.message, {icon: 1});
                                        tableRender();
                                        layer.close(index);

                                    } else
                                        layer.alert(result.message, {icon: 1});
                                }
                            } else {
                                layer.msg("该组名已存在");
                                body.find("#name").focus();
                            }
                        });
                        body.find("#cancel").click(function () {
                            layer.close(index);
                        });
                        iframeWin.layui.form.render();
                    }
                })
                break;
        }
        ;
    });

    //监听行工具事件
    table.on('tool(demo)', function (obj) {
        var data = obj.data;
        console.log(obj);
        if (obj.event === 'manage') {
            layer.open({
                type: 2,
                title: "小组人员管理",
                area: ['100%', '100%'],
                content: ["TeamMember.html"],
                shadeClose: true, //点击旁边地方自动关闭
                //动画
                anim: 0,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    let teamId = data.id;//得到小组id
                    let result = myAjax("/user/getTeamUser", "get", {teamId: teamId});
                    let teamMember = result.data.members;//得到未分组成员和该小组成员
                    let teamMemberIds = [];
                    $.each(teamMember, function (key, val) {
                        teamMemberIds.push(val.id);//取得未分组成员和该小组成员的id值
                    });
                    //获取组内成员id数
                    let rightIds = result.data.inTeamMemberIds;
                    console.log("rightIds");
                    console.log(rightIds);
                    //获取未分组成员id
                    let leftIds = teamMemberIds.filter(function (item) {
                        return rightIds.indexOf(item) == -1;//等于未分组成员和该小组成员的id值去掉该小组成员id
                    })
                    let left = [];
                    let right = [];
                    console.log("leftIds");
                    console.log(leftIds);
                    let transfer = iframeWin.layui.transfer;
                    console.log(transfer);
                    transfer.render({
                        elem: body.find("#team_member"),
                        title: ["未分配组员", "该组内成员"],
                        data: teamMember,
                        parseData: function (res) {
                            let title = "";
                            if (res.name != null)
                                title = res.code + "(" + res.name + ")";
                            else
                                title = res.code;
                            return {
                                "value": res.id,
                                "title": title
                            };
                        },
                        value: rightIds,
                        showSearch: true,
                        onchange: function (data, index) {
                            console.log(data); //得到当前被穿梭的数据
                            console.log(index); //如果数据来自左边，index 为 0，否则为 1
                            let dataIds = [];
                            //将移动的数据的id提取出来
                            $.each(data, function (key, val) {
                                dataIds.push(val.value);
                            });
                            if (index == 0) {//如果数据来自左边，则将左边相同数据移除
                                left = left.filter(function (item) {
                                    return dataIds.indexOf(item) == -1;
                                });
                                //将移除的数据加入右边
                                $.each(dataIds, function (key, val) {
                                    right.push(val);
                                });
                                right = right.filter(function (item) {
                                    return rightIds.indexOf(item) == -1;
                                });
                            } else if (index == 1) {//如果数据来自右边，则将右边相同数据移除
                                right = right.filter(function (item) {
                                    return dataIds.indexOf(item) == -1;
                                });
                                //将移动的数据加入到左边
                                $.each(dataIds, function (key, val) {
                                    left.push(val);
                                });
                                left = left.filter(function (item) {
                                    return leftIds.indexOf(item) == -1;
                                });
                            }
                            console.log("left");
                            console.log(left);
                            console.log("right");
                            console.log(right);
                            console.log("leftIds");
                            console.log(leftIds);
                            console.log("rightIds");
                            console.log(rightIds);
                        }
                    });
                    body.find("#save").click(function () {
                        //获得右侧数据
                        // let getData = iframeWin.layui.transfer.getData('team');
                        // console.log(getData);
                        let datas = {
                            "left": JSON.stringify(left),
                            "right": JSON.stringify(right),
                            "teamId": teamId
                        }
                        let result = myAjax("/userTeam/setUserTeam", "post", datas);
                        if (result) {
                            layer.alert(result.message, {icon: 1});
                            tableRender();//刷新小组列表
                            layer.close(index);
                        } else
                            layer.alert(result.message);

                    });
                    body.find(("#cancel")).click(function () {
                        layer.close(index);
                    });
                }
            })
        } else if (obj.event === 'del') {
            layer.confirm("真的删除小组" + data.name + "?", function (index) {
                // obj.del();
                let result = myAjax("/team/deleteTeam", "get", {id: data.id});
                alert(result.message);
                tableRender();
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            // layer.alert(JSON.stringify(obj.data));
            layer.open({
                type: 2,
                title: "修改小组信息",
                area: ['100%', '100%'],
                content: ["editTeam.html"],
                shadeClose: true, //点击旁边地方自动关闭
                //动画
                anim: 0,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    //给表单赋值
                    let teamMembers = myAjax("/user/getTeamMember", "get", {"teamId": data.id});
                    let members = teamMembers.data;
                    console.log(members);
                    if (members == "[]")
                        body.find("#leader").html("<option value=''>暂无</option>");
                    else {
                        $.each(members, function (i, member) {
                            if (member.name != null && member.name != '')
                                body.find("#leader").append("<option value='" + member.code + "'>" + member.code + "(" + member.name + ")" + "</option>");
                            else
                                body.find("#leader").append("<option value='" + member.code + "'>" + member.code + "</option>");
                        })
                    }
                    let coaches = myAjax("/user/getCoachList", "get");
                    let coachs = coaches.data;
                    if (coachs == "[]")
                        body.find("#coach").html("<option value=''>暂无</option>");
                    else {
                        $.each(coachs, function (i, coach) {
                            if (coach.name != null && coach.name != '')
                                body.find("#coach").append("<option value='" + coach.code + "'>" + coach.code + "(" + coach.name + ")" + "</option>");
                            else
                                body.find("#coach").append("<option value='" + coach.code + "'>" + coach.code + "</option>");
                        })
                    }
                    body.find("#name").val(data.name);
                    body.find("#name").attr("disabled", "disabled");
                    body.find("#desc").val(data.description);
                    body.find("#stage").val(data.stage);
                    body.find("#clazzRoom").val(data.clazzRoom);
                    body.find("#leader").find("option[value='" + data.leader + "']").prop("selected", "selected");
                    let preLeader = body.find("#leader").find("option:selected").val();
                    body.find("#coach").find("option[value='" + data.coach + "']").prop("selected", "selected");
                    let leader = "";
                    // body.find("#leader").change(function () {
                    //     leader = body.find("#leader").find("option:selected").val();
                    //     console.log(leader);
                    // });
                    iframeWin.layui.form.on("select(leader)",function () {
                        leader = body.find("#leader").find("option:selected").val();
                        console.log(leader);
                    })
                    body.find("#update").click(function () {
                        let name = body.find("#name").val();
                        let desc = body.find("#desc").val();
                        let stage = body.find("#stage").val();
                        let clazzRoom = body.find("#clazzRoom").val();
                        if (leader != "") {
                            let res = myAjax("/userRole/changeLeader", "post", {preLeader: preLeader, leader: leader});
                            console.log(res.message);
                        } else
                            leader = preLeader;
                        let teamdata = {
                            "id": data.id,
                            "name": name,
                            "description": desc,
                            "stage": stage,
                            "clazzRoom": clazzRoom,
                            "leader": leader,
                            "coach": body.find("#coach").find("option:selected").val()
                        };
                        console.log(teamdata);
                        let result = ajaxModel("/team/updateTeam", "post", teamdata);
                        layer.alert(result.message, {icon: 1});
                        if (result.code == 200) {
                            tableRender();
                            layer.close(index);
                        }
                    });
                    body.find("#cancel").click(function () {
                        layer.close(index);
                    });
                    iframeWin.layui.form.render();
                }
            })
        }
    });

    //获取码表数据
    function getLeader() {
        let data = null;
        if (sessionStorage.getItem("leader") != null) {
            data = JSON.parse(sessionStorage.getItem("leader"));
        } else {
            let result = ajaxModel("/user/getLeaderList", "get");
            data = result.data;
            sessionStorage.setItem("leader", JSON.stringify(data));
        }
        console.log(data);
        $("#leader").html("<option value=''>全部</option>");
        $.each(data, function (i, leader) {
            if (leader.name != null)
                $("#leader").append("<option value='" + leader.code + "'>" + leader.code + "(" + leader.name + ")" + "</option>");
            else
                $("#leader").append("<option value='" + leader.code + "'>" + leader.code + "</option>");
        })
    }

    function getCoach() {
        let data = null;
        if (sessionStorage.getItem("coach") != null) {
            data = JSON.parse(sessionStorage.getItem("coach"));
        } else {
            let result = ajaxModel("/user/getCoachList", "get");
            data = result.data;
            sessionStorage.setItem("coach", JSON.stringify(data));
        }
        console.log(data);
        $("#coach").html("<option value=''>全部</option>");
        $.each(data, function (i, coach) {
            if (coach.name != null && coach.name != '')
                $("#coach").append("<option value='" + coach.code + "'>" + coach.code + "(" + coach.name + ")" + "</option>");
            else
                $("#coach").append("<option value='" + coach.code + "'>" + coach.code + "</option>");
        });
    }
});
